<?php

class AuthController extends Controller {

	public function __construct() {
		parent::__construct();
	}

	public function loginAction() {
		$ip = $_SERVER['REMOTE_ADDR'];
		$query = "SELECT 
			u.`id` AS `id`,
			u.`name` AS `name`,
			u.`avatar` AS `avatar`,
			u.`ip` AS `ip`,
			u.`flag` AS `flag`,
			u.`group` as `group`,
			g.`name` as `groupName`
			FROM `user` AS u 
			LEFT JOIN `group` AS g 
				ON u.`group`=g.`id` 
			WHERE `ip`='{$ip}'";
		$db = $this->loadSqlite('bamboo');
		$row = $db->getOne($query);
		if(empty($row)) {
			$this->jsonError("", array(), 2);
		}
		if(!$row['flag'] || !$row['group']){
			$this->jsonError("您的IP [{$ip}] 已提交申请，尚未开通。");
		}
		if(empty($row['avatar'])) $row['avatar'] = 'avatar.png';
		$_SESSION['uid'] = (int) $row['id'];
		session_write_close();
		$this->jsonSuccess('', $row);
	}

	public function genAction(){
		$files = scandir(PATH_ROOT . '/php/controllers/');
		$tmpl = "<ul class=\"btn\"><li><a href=\"javascript:void(0);\" class=\"gen\">重新生成模版</a></li></ul>\n";
		$tmpl .= "<form action=\"#\" method=\"\">\n\t<div class=\"row\"><label>group</label><select name=\"id\"><option value=\"0\">Loading</option></select></div>\n";
		foreach($files as $file){
			if(in_array($file, array('.', '..', '.svn','CommonController.class.php', __CLASS__.'.class.php'))){
				continue;
			}
			
			include PATH_ROOT . '/php/controllers/' . $file;
			$controller = str_replace(".class.php", "", $file);
			$ref = new ReflectionClass(new $controller());
			$data = $ref->getMethods(ReflectionMethod::IS_PUBLIC);

			$controllerName = str_ireplace('Controller', '', $controller);
			$tmpl .= "\t<div class=\"row\">\n\t\t<label>{$controllerName}</label>\n\t\t<ul>\n";
			foreach ($data as $item) {
				if(preg_match("/Action$/", $item->name)) {
					$actionName = str_ireplace('Action', '', $item->name);
					$tmpl .= "\t\t\t<li><input type=\"checkbox\" name=\"permission[]\" value=\"{$controllerName}.{$actionName}\"/><span class=\"label-r\">{$actionName}</span></li>\n";
				}
			}
			$tmpl .= "\t\t</ul>\n\t</div>\n";
		}

		$tmpl .= "\t<div class=\"button\">\n\t\t<input type=\"submit\" />\n\t</div>\n</form>";

		file_put_contents(PATH_ROOT . '/tmpl/permission.html', $tmpl);

		$this->jsonSuccess('模版生成成功');
	}

	public function applyAction() {
		$data = array(
			'group' => 4,
			'name' => $this->requestPost('name'),
			'ip' => $_SERVER['REMOTE_ADDR'],
			'avatar' => 'avatar.png',
			'flag' => 1
		);

		if(empty($data['name'])) {
			$this->jsonError('请填写您的大名');
		}

		$db = $this->loadSqlite('bamboo');

		if($db->set('user', $data)) {
			$this->jsonSuccess('恭喜注册成功，5秒后刷新页面。');
		} else  {
			$this->jsonError('数据存储失败，请联系开发人员。');
		}
	}
	
}

?>
